package db.threads;

import java.util.concurrent.Future;

import core.exceptions.DBAccessException;
import core.threads.ThreadCallable;
import core.threads.ThreadPool;

public class DBAccessThread {
	
	private IDBAccessThread handler;
	
	private DBAccessThread(IDBAccessThread handler) {
		this.handler = handler;
	}
	
	public static void invoke(final IDBAccessThread handler) {
		
		final DBAccessThread thread = new DBAccessThread(handler);
		
		ThreadPool.submitTask(new ThreadCallable<Future<Void>, Void>() {

			@Override
			public Void call() throws Exception {
				try {
					thread.runThread();
				} catch (Exception e) {
					if (handler != null) {
						//this is not DBAccessException, since we've handled it in runThread()
						//wrap it with DBAccessException and notify caller:
						handler.onAccessFailed(new DBAccessException("Unknown error", e));
					} else {
						throw e;
					}
				}
				//when runThread() finishes, setArgument with any value,
				//and thread will be released from the pool:
				setArgument(null);
				return null;				
			}
			
		});
		
	}
	
	private void runThread() throws DBAccessException {
	
		try {
			if (handler != null) {
				handler.onAccessFinished(handler.onCreateQuery());
			}
		} catch (DBAccessException e) {
			if (handler != null) {
				handler.onAccessFailed(e);
			} else {
				throw e;
			}
		}
		
	}

}
